/**
 * 远程搜索工具
 * @file
 * @date 2018-12-20 10:55:02
 */

layui.define(['select2'], function (exports) {
    var $ = layui.$;

    var select = {
        create: function (option) {
            var rSelect = new RemoteSelect(option);
            return rSelect.instance;
        }
    };

    function RemoteSelect (options) {
        if (!options) {
            return;
        }

        $.extend(this.options, options);

        this.init();
    }

    RemoteSelect.prototype.instance = null;

    RemoteSelect.prototype.getConfig = function () {
        return {
            theme: "layui",
            language: 'zh-CN',
            placeholder: '全部',
            allowClear: true,
            minimumInputLength: 1,
            dropdownAutoWidth: true,
            ajax: {
            url: url,
                dataType: 'json',
                delay: 250,
                data: this.options.query,
                processResults: function (response) {
                    var results = [];
                    if (response.status === 200) {
                        results = response.data;
                    }
                    results = results.map((item) => {
                        item.id = item.value;
                        return item;
                    });

                    return {
                        results: results
                    };
                }
            },
            escapeMarkup: this.options.escapeMarkup,
            templateResult: this.options.templateResult
        }
    }

    RemoteSelect.prototype.options = {
        elem: '',
        url: '',
        query: function () {
            var query = {
                text: params.term
            }
            return query;
        },
        escapeMarkup: function (markup) { return markup; },
        templateResult: function () {
            if (repo.loading) {
                return '查询中...'
            }
            return repo.text;
        },
    };

    RemoteSelect.prototype.init = function () {
        var config = this.getConfig();
        this.instance = $(this.options.elem).select2(config);
    }

    exports('remoteSelect', select);
});